package com.example.system.service.question;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.core.constants.Constants;
import com.example.common.core.enums.ResultCode;
import com.example.security.exception.ServiceException;
import com.example.system.controller.question.QuestionController;
import com.example.system.domain.question.Question;
import com.example.system.domain.question.dto.QuestionAddDTO;
import com.example.system.domain.question.dto.QuestionEditDTO;
import com.example.system.domain.question.dto.QuestionQueryDTO;
import com.example.system.domain.question.es.QuestionES;
import com.example.system.domain.question.vo.QuestionDetailVO;
import com.example.system.domain.question.vo.QuestionVO;
import com.example.system.elasticsearch.QuestionRepository;
import com.example.system.manager.QuestionCacheManager;
import com.example.system.mapper.question.QuestionMapper;
import com.github.pagehelper.PageHelper;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 23050
 * @version 1.0
 * @description: TODO
 * @date 2025/2/16 20:24
 */
@Service
public class QuestionServiceImpl implements QuestionService{

    @Resource
    private QuestionMapper questionMapper;

    @Autowired
    private QuestionRepository questionRepository;

    @Resource
    private QuestionCacheManager questionCacheManager;

    //查询题目列表
    @Override
    public List<QuestionVO> list(QuestionQueryDTO questionQueryDTO) {
        if (StrUtil.isNotEmpty(questionQueryDTO.getExcludeStr())){
            //判断当前竞赛是否有题目，存在则分割并解析
            String excludeStr = questionQueryDTO.getExcludeStr();
            String[] excludeArr = excludeStr.split(Constants.SPLIT_SEM);
            //通过stream流去重
            Set<Long> excludeIdSet = Arrays.stream(excludeArr)
                    .map(Long::valueOf)
                    .collect(Collectors.toSet());
            questionQueryDTO.setExcludeIdSet(excludeIdSet);
        }
        PageHelper.startPage(questionQueryDTO.getPageNum(),questionQueryDTO.getPageSize());
        return questionMapper.selectQuestionList(questionQueryDTO);

    }

    //添加题目
    @Override
    public int add(QuestionAddDTO questionAddDTO) {

        List<Question> questionList = questionMapper.selectList(
                new LambdaQueryWrapper<Question>()
                        .eq(Question::getTitle, questionAddDTO.getTitle())
        );
        if (CollectionUtil.isNotEmpty(questionList)){
            throw new ServiceException(ResultCode.FAILED_ALREADY_EXISTS);
        }
        Question question = new Question();
        //使用hutool工具类复制类
        BeanUtil.copyProperties(questionAddDTO,question);
        int ret = questionMapper.insert(question);
        if (ret<=0){
            return 0;
        }
        //往es中插入数据
        QuestionES questionES = new QuestionES();
        BeanUtil.copyProperties(question,questionES);
        questionRepository.save(questionES);
        questionCacheManager.addCache(question.getQuestionId());
        return 1;
    }

    //查询题目详情
    @Override
    public QuestionDetailVO detail(Long questionId) {
        Question question = questionMapper.selectById(questionId);
//        System.out.println("questionId:"+questionId);
        if (question == null){
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        QuestionDetailVO questionDetailVO = new QuestionDetailVO();
        BeanUtil.copyProperties(question,questionDetailVO);
        return questionDetailVO;

    }

    //编辑题目详情
    @Override
    public int edit(QuestionEditDTO questionEditDTO) {
        Question oldQuestion = questionMapper.selectById(questionEditDTO.getQuestionId());
        if (oldQuestion==null){
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        oldQuestion.setTitle(questionEditDTO.getTitle());
        oldQuestion.setDifficulty(questionEditDTO.getDifficulty());
        oldQuestion.setTimeLimit(questionEditDTO.getTimeLimit());
        oldQuestion.setSpaceLimit(questionEditDTO.getSpaceLimit());
        oldQuestion.setContent(questionEditDTO.getContent());
        oldQuestion.setQuestionCase(questionEditDTO.getQuestionCase());
        oldQuestion.setDefaultCode(questionEditDTO.getDefaultCode());
        oldQuestion.setMainFunc(questionEditDTO.getMainFunc());

        QuestionES questionES = new QuestionES();
        BeanUtil.copyProperties(oldQuestion,questionES);
        questionRepository.save(questionES);
        return questionMapper.updateById(oldQuestion);
    }

    //删除题目
    @Override
    public int delete(Long questionId) {
        Question question = questionMapper.selectById(questionId);
        if (question == null){
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        //es中删除
        questionRepository.deleteById(questionId);
        //Redis中删除
        questionCacheManager.deleteCache(questionId);
        return questionMapper.deleteById(questionId);
    }


}
